package com.ruoyi.index.userController;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cyl.h5.config.SecurityUtil;
import com.cyl.h5.service.H5FhMypunctuationService;
import com.cyl.manager.act.domain.entity.FhMypunctuation;
import com.cyl.manager.message.domain.entity.FhIndexMessage;
import com.cyl.manager.message.domain.query.FhIndexMessageQuery;
import com.cyl.manager.message.service.FhIndexMessageService;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.github.pagehelper.PageInfo;
import com.ruoyi.chat.domain.FhChatFriend;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.index.domain.*;
import com.ruoyi.index.dto.FhMapFishtypeDto;
import com.ruoyi.index.dto.PostInfoDtoX;
import com.ruoyi.index.dto.PostinfoDto;
import com.ruoyi.index.service.IFhIndexHotService;
import com.ruoyi.index.service.IFhIndexLikeService;
import com.ruoyi.index.service.IFhIndexPostcommentsService;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.index.service.impl.FhIndexPostinfoDetailService;
import com.ruoyi.index.service.impl.IndexPostcommentsLikeService;
import com.ruoyi.info.domain.*;
import com.ruoyi.info.service.*;
import com.ruoyi.map.domain.FhMapFishtype;
import com.ruoyi.map.domain.FhMapWater;
import com.ruoyi.map.service.IFhMapFishtypeService;
import com.ruoyi.map.service.IFhMapWaterService;
import com.ruoyi.tokenTools.UserLoginToken;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
/**
 * 发布信息Controller
 *
 * @author ruoyi
 * @date 2024-11-11
 */
@Api(tags = "首页接口")
@RestController
@RequestMapping("/app/index/postinfo")
@Slf4j
public class UserFhIndexPostinfoController extends BaseController {
    @Autowired
    private IFhIndexPostinfoService fhIndexPostinfoService;

    @Autowired
    private IFhIndexPostcommentsService iFhIndexPostcommentsService;

    @Autowired
    private IFhIndexLikeService iFhIndexLikeService;

    @Autowired
    private IFhChatFriendService iFhChatFriendService;

    @Autowired
    private IFhIndexHotService iFhIndexHotService;

    @Autowired
    private IFhInfoUserService fhInfoUserService;

    @Autowired
    private IFhInfoCatchrecordService fhInfoCatchrecordService;

    @Autowired
    private IFhInfoMyspaceService fhInfoMyspaceService;

    @Autowired
    private IFhInfoExperienceService fhInfoExperienceService;

    @Autowired
    private IFhMapFishtypeService fhMapFishtypeService;

    @Autowired
    private IFhInfoUsertaskService fhInfoUsertaskService;

    @Autowired
    private IFhInfoFishpointService fhInfoFishpointService;

    @Autowired
    private IFhMapWaterService fhMapWaterService;

    @Autowired
    private IFhChatFriendService fhChatFriendService;

    @Autowired
    private FhIndexPostinfoDetailService fhIndexPostinfoDetailService;

    @Autowired
    private FhInfoEquipService fhInfoEquipService;
    @Autowired
    private FhIndexMessageService fhIndexMessageService;

    @Autowired
    private IFhIndexPostcommentsService fhIndexPostcommentsService;

    @Autowired
    private IFhIndexLikeService fhIndexLikeService;

    @Autowired
    private H5FhMypunctuationService h5FhMypunctuationService;
    /**
     * 首页推荐列表
     */
    @UserLoginToken
    @ApiOperation("首页推荐列表查询")
    @GetMapping("/indexList")
    public R<TableDataInfo> list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {

            TableDataInfo tableDataInfo = new TableDataInfo();
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            //查询发布信息列表
            startPage();
            List<FhIndexPostinfoAndIsLike>  fhIndexPostinfoAndIsLike= fhIndexPostinfoService.selectFhIndexPostinfoListAndIsLike(userId);
            //通过发布信息列表，获得返回数据列表
            List<IndexInfoListVo> indexInfoListVoList = selectPostInfo(fhIndexPostinfoAndIsLike);
            tableDataInfo.setTotal(new PageInfo<>(indexInfoListVoList).getTotal());
            tableDataInfo.setRows(indexInfoListVoList);
            return R.ok(tableDataInfo);

    }

    @ApiOperation("删除我的发布")
    @DeleteMapping("/postinfoDelete")
    public R<String> postinfoDelete(Long id) throws IOException {
        try {
            fhIndexPostinfoService.deleteFhIndexPostinfoById(id);
            return R.ok("操作成功");
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
    /**
     * 安全地获取唯一的渔获记录
     * @param userId 用户ID
     * @return 渔获记录对象，如果不存在或存在重复则返回null
     */
    private FhInfoCatchrecord getUniqueCatchrecord(Long userId) {
        try {
            // 使用查询列表方法替代selectOne
            FhInfoCatchrecord queryRecord = new FhInfoCatchrecord();
            queryRecord.setUserId(userId);
            List<FhInfoCatchrecord> recordList = fhInfoCatchrecordService.selectFhInfoCatchrecordList(queryRecord);

            if (recordList == null || recordList.isEmpty()) {
                log.debug("未找到用户渔获记录，用户ID: {}", userId);
                return null;
            }

            if (recordList.size() > 1) {
                log.warn("发现重复渔获记录数据，用户ID: {}，记录数: {}", userId, recordList.size());
                // 记录详细信息用于问题排查
                for (FhInfoCatchrecord record : recordList) {
                    log.warn("重复记录ID: {}, 创建时间: {}", record.getId(), record.getCrateTime());
                }
            }

            // 返回第一条记录
            return recordList.get(0);
        } catch (Exception e) {
            log.error("查询渔获记录异常，用户ID: {}", userId, e);
            return null;
        }
    }
    /**
     * 首页关注推荐列表
     */
    @UserLoginToken
    @ApiOperation("首页关注列表查询")
    @GetMapping("/indexFollowList")
    public R<TableDataInfo> indexFollowList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        try {
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();

            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            List<FhChatFriend> fhChatFriendList = iFhChatFriendService.selectFhChatFriendList(fhChatFriend);

            // 如果没有关注的好友，直接返回空数据
            if (fhChatFriendList == null || fhChatFriendList.isEmpty()) {
                TableDataInfo tableDataInfo = new TableDataInfo();
                tableDataInfo.setTotal(0);
                tableDataInfo.setRows(Collections.emptyList());
                return R.ok(tableDataInfo);
            }

            ArrayList<Long> friends = new ArrayList<>();
            for (FhChatFriend friend : fhChatFriendList) {
                friends.add(friend.getFriendId());
            }

            startPage();

            // 查询发布信息
            List<FhIndexPostinfoAndIsLike> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoListAndIsLikeByIds(userId, friends);
            List<IndexInfoListVo> indexInfoListVoList = selectPostInfo(fhIndexPostinfoList);

            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(new PageInfo(fhIndexPostinfoList).getTotal());
            tableDataInfo.setRows(indexInfoListVoList);

            return R.ok(tableDataInfo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 首页附近列表
     */
    @UserLoginToken
    @ApiOperation("首页附近列表查询")
    @GetMapping("/indexNearbyList")
    public R<TableDataInfo> indexNearbyList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                                    String longitude,
                                                    String latitude
    ) {
        try {
            startPage();
            //根据经度，纬度查询捕获表
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            List<FhIndexPostinfoAndIsLike> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoListAndIsLikeByNW(longitude,latitude,userId);
            List<IndexInfoListVo> indexInfoListVoList = selectPostInfo(fhIndexPostinfoList);
            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(new PageInfo<>(fhIndexPostinfoList).getTotal());
            tableDataInfo.setRows(indexInfoListVoList);
            return R.ok(tableDataInfo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 帖子详情
     */
    @UserLoginToken
    @ApiOperation("帖子详情")
    @GetMapping("/postDetial")
    public R<IndexInfoListVo> postDetial(Long postId) {
        try {
            IndexInfoListVo indexInfoListVo = new IndexInfoListVo();
            UserInfo localUserInfo = LocalUserInfoUtil.getLocalUserInfo();
            //发布详情
            FhIndexPostinfo fhIndexPostinfo = fhIndexPostinfoService.selectFhIndexPostinfoById(postId);
            //插入是否关注
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(localUserInfo.getId());
            fhChatFriend.setFriendId(fhIndexPostinfo.getUserId());
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            if(!fhChatFriends.isEmpty()){
                indexInfoListVo.setFollow(true);
            }else {
                indexInfoListVo.setFollow(false);
            }
            //插入用户信息和是否点赞
            UserInfoAndIsFollow userInfoAndIsFollow  = fhInfoUserService.selectUserInfoAndFollowStatus(fhIndexPostinfo.getUserId(),localUserInfo.getId());
            indexInfoListVo.setUserInfoAndIsFollow(userInfoAndIsFollow);
            FhIndexLike fhIndexLike = new FhIndexLike();
            fhIndexLike.setUserId(localUserInfo.getId());
            fhIndexLike.setPostinfoId(postId);
            //插入是否点赞
            List<FhIndexLike> fhIndexLikes = fhIndexLikeService.selectFhIndexLikeList(fhIndexLike);
            if(!fhIndexLikes.isEmpty()){
                indexInfoListVo.setLike(true);
            }else {
                indexInfoListVo.setLike(false);
            }
            //插入发布信息
            indexInfoListVo.setFhIndexPostinfo(fhIndexPostinfo);
            //插入发布鱼中名称
            String fishIds = fhIndexPostinfo.getFishIds();
            String[] fishIdList = fishIds.split(",");
            String[] fishNameList = new String[fishIdList.length];
            for (int j = 0; j < fishIdList.length; j++) {
                Long fishId = Long.valueOf(fishIdList[j]);
                FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(fishId);
                fishNameList[j] = fhMapFishtype.getFishType();
            }
            String postInfoFishS = String.join(",", fishNameList);
            indexInfoListVo.setPostInfoFishS(postInfoFishS);
            return R.ok(indexInfoListVo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 搜索动态
     */
    @UserLoginToken
    @ApiOperation("搜索动态")
    @GetMapping("/indexSelectList")
    public R<TableDataInfo> indexSelectList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                            String terms
    ) {
        try {
            startPage();
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            //根据发布内容,或热点词查询
            List<FhIndexPostinfoAndIsLike> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoListAndIsLikeByTerms(terms,userId);
            List<IndexInfoListVo> indexInfoListVoList = selectPostInfo(fhIndexPostinfoList);
            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(new PageInfo<>(fhIndexPostinfoList).getTotal());
            tableDataInfo.setRows(indexInfoListVoList);
            return R.ok(tableDataInfo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 渔获详情
     */
    @UserLoginToken
    @ApiOperation("渔获详情")
    @GetMapping("/indexPostInfoDetails")
    public R<PostInfoDetailVo> indexPostInfoDetails(Long postInfoId) {
        try {
            FhIndexPostinfo fhIndexPostinfo = fhIndexPostinfoService.selectFhIndexPostinfoById(postInfoId);
            if(fhIndexPostinfo==null){
                return R.fail("此条动态不存在");
            }
            /**
             * 返回数据
             */
            PostInfoDetailVo postInfoDetailVo = new PostInfoDetailVo();
            //查询水域名
            FhMapWater fhMapWater = new FhMapWater();
            fhMapWater.setLongitude(fhIndexPostinfo.getLongitude());
            fhMapWater.setLatitude(fhIndexPostinfo.getLatitude());
            List<FhMapWater> fhMapWaters = fhMapWaterService.selectFhMapWaterList(fhMapWater);
            if(fhMapWaters!=null&&!fhMapWaters.isEmpty()){
                postInfoDetailVo.setWaterName(fhMapWaters.get(0).getWaterName());
            }
            //天气信息
            postInfoDetailVo.setWeather(fhIndexPostinfo.getWeather());
            postInfoDetailVo.setTemperature(fhIndexPostinfo.getTemperature());
            postInfoDetailVo.setSd(fhIndexPostinfo.getSd());
            postInfoDetailVo.setWeatherCode(fhIndexPostinfo.getWeatherCode());
            postInfoDetailVo.setAirPress(fhIndexPostinfo.getAirPress());
            //位置信息
            postInfoDetailVo.setLon(fhIndexPostinfo.getLongitude());
            postInfoDetailVo.setLat(fhIndexPostinfo.getLatitude());
            postInfoDetailVo.setLocationName(fhIndexPostinfo.getUserLocation());
            postInfoDetailVo.setLocaltionType(fhIndexPostinfo.getLocationType());
            //渔获详情
            List<FhIndexPostinfoDetail> postinfoDetailList =  fhIndexPostinfoDetailService.selectListByPostId(postInfoId);
            for (FhIndexPostinfoDetail fhIndexPostinfoDetail : postinfoDetailList) {
                fhIndexPostinfoDetail.setFishingType(fhIndexPostinfo.getFishingPractice());
            }
            postInfoDetailVo.setPostinfoDetailList(postinfoDetailList);
            //装备列表
            String equips = fhIndexPostinfo.getEquips();
            if(equips==null||equips.isEmpty()){
                return R.ok(postInfoDetailVo);
            }
            String[] split = equips.split(",");
            Long[] equipIds = new Long[split.length];
            for (int i = 0; i < split.length; i++) {
                equipIds[i] = Long.parseLong(split[i]) ;
            }
            List<FhInfoEquip> fhInfoEquips = fhInfoEquipService.selectListByIdList(equipIds);
            postInfoDetailVo.setEquipList(fhInfoEquips);

            return R.ok(postInfoDetailVo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 返回用户发布信息列表方法
     */
    public List<IndexInfoListVo> selectPostInfo(List<FhIndexPostinfoAndIsLike> fhIndexPostinfoList) {
        UserInfo localUserInfo = LocalUserInfoUtil.getLocalUserInfo();
        //返回的数据
        List<IndexInfoListVo> indexInfoListVoList = new ArrayList<>();
        for (int i = 0; i < fhIndexPostinfoList.size(); i++) {
            IndexInfoListVo indexInfoListVo = new IndexInfoListVo();
            //获取发布信息id
            Long postId = fhIndexPostinfoList.get(i).getId();
            Boolean isLike = fhIndexPostinfoList.get(i).getIsLike();
            // 查询用户信息和是否关注
            Long frinedId = fhIndexPostinfoList.get(i).getUserId();
            Long userId = localUserInfo.getId();
            UserInfoAndIsFollow userInfoAndIsFollow = fhInfoUserService.selectUserInfoAndFollowStatus(frinedId, userId);
//            indexInfoListVo.setFhInfoUser(userInfoAndIsFollow.getFhInfoUser());
            indexInfoListVo.setUserInfoAndIsFollow(userInfoAndIsFollow);
            //插入发布信息
            indexInfoListVo.setFhIndexPostinfo(fhIndexPostinfoList.get(i));
            //插入发布鱼中名称
            String fishIds = fhIndexPostinfoList.get(i).getFishIds();
            if (fishIds == null || fishIds.isEmpty()) {
                indexInfoListVo.setPostInfoFishS("未知");
                continue;
            }
            String[] fishIdList = fishIds.split(",");
            //改为查询单条鱼名称
            FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(Long.valueOf(fishIdList[0]));
            if (fhMapFishtype == null) {
                log.warn("找不到ID为 {} 的鱼种", fishIdList[0]);
                indexInfoListVo.setPostInfoFishS("未知");
            } else {
                indexInfoListVo.setPostInfoFishS(fhMapFishtype.getFishType());
            }
            //插入是否点赞
            indexInfoListVo.setLike(isLike);
            //将添加完毕的数据放入返回体

            FhIndexPostcomments fhIndexPostcommen = new FhIndexPostcomments();
            fhIndexPostcommen.setPostinfoId(postId);
            List<FhIndexPostcomments> fhIndexPostcommentsList = iFhIndexPostcommentsService.selectFhIndexPostcommentsList(fhIndexPostcommen);
            indexInfoListVo.setFhIndexPostcommentsList(fhIndexPostcommentsList);

            indexInfoListVoList.add(indexInfoListVo);
        }
        return indexInfoListVoList;
    }


    /**
     * 新增发布信息
     */
    @UserLoginToken
    @ApiOperation("发布")
    @PostMapping
    @Transactional
    public R<String> add(@RequestBody IndexInfoListDto indexInfoListDto) {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            /**
             * 使用正则截取出前面@用户名和#关键字
             */
            String postText = indexInfoListDto.getPostText();
            // 定义正则表达式，匹配@后跟任意字符（非贪婪），直到遇到空格或字符串结束，并使用捕获组来获取@后面的部分
            String regex = "@([^\\s]+)";
            String regex1 = "#([^\\s]+)";
            // 编译正则表达式
            Pattern pattern = Pattern.compile(regex);
            Pattern pattern1 = Pattern.compile(regex1);
            // 创建匹配器
            Matcher matcher = pattern.matcher(postText);
            Matcher matcher1 = pattern1.matcher(postText);
            // 存储匹配结果的列表,@用户名列表，#关键词列表
            List<String> userName = new ArrayList<>();
            List<String> hot = new ArrayList<>();
            // 查找所有匹配项
            while (matcher.find()) {
                // 由于使用了捕获组，我们可以直接通过group(1)来获取第一个捕获组的内容
                userName.add(matcher.group(1));
            }
            while (matcher1.find()){
                hot.add(matcher1.group(1));
            }
            String shareName = String.join(",",userName);
            String hotWords = String.join(",",hot);
            /**
             * 拼接渔获ids
             */
            String postinfoDetailListString = indexInfoListDto.getPostinfoDetailList();
            JSONArray jsonArray = JSON.parseArray(postinfoDetailListString);
            // 创建一个 List 来存储解析后的 FhIndexPostinfoDetail 对象
            List<FhIndexPostinfoDetail> postinfoDetailList = new ArrayList<>();
            // 遍历 JSONArray，将每个 JSONObject 解析为 FhIndexPostinfoDetail 对象，并添加到列表中
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                FhIndexPostinfoDetail postinfoDetail = new FhIndexPostinfoDetail();
                // 假设 FhIndexPostinfoDetail 类有相应的 setter 方法来设置属性值
                postinfoDetail.setFishId(jsonObject.getLong("id"));
                postinfoDetail.setWeight(jsonObject.getDouble("weight"));
                postinfoDetail.setLength(jsonObject.getDouble("length"));
                postinfoDetailList.add(postinfoDetail);
            }
            //postinfoDetailList 判断是否为空
            if (postinfoDetailList.isEmpty()){
                return R.fail("发布的渔获不能为空");
            }
            List<String> fishIdList = new ArrayList<>();
            for (int i = 0; i < postinfoDetailList.size(); i++) {
                fishIdList.add(String.valueOf(postinfoDetailList.get(i).getFishId()));
            }
            String fishIds = String.join(",",fishIdList);
            /**
             * 发布的用户信息
             */
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            /**
             * 插入发布信息表数据
             */
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setUserId(userId);
            fhIndexPostinfo.setUserName(fhInfoUser.getName());
            fhIndexPostinfo.setUserImage(fhInfoUser.getImage());
            fhIndexPostinfo.setLongitude(indexInfoListDto.getLongitude());
            fhIndexPostinfo.setLatitude(indexInfoListDto.getLatitude());
            fhIndexPostinfo.setUserLocation(indexInfoListDto.getUserLocation());
            fhIndexPostinfo.setLocationType(indexInfoListDto.getLocationType());
            fhIndexPostinfo.setPostImages(indexInfoListDto.getPostImages());
            fhIndexPostinfo.setShareName(shareName);
            fhIndexPostinfo.setHotWords(hotWords);
            fhIndexPostinfo.setPostText(indexInfoListDto.getPostText());
            fhIndexPostinfo.setPostTime(indexInfoListDto.getPostTime());
            fhIndexPostinfo.setEquips(indexInfoListDto.getEquips());
            fhIndexPostinfo.setFishingPractice(indexInfoListDto.getFishingPractice());
            fhIndexPostinfo.setWeather(indexInfoListDto.getWeather());
            fhIndexPostinfo.setTemperature(indexInfoListDto.getTemperature());
            fhIndexPostinfo.setSd(indexInfoListDto.getSd());
            fhIndexPostinfo.setWeatherCode(indexInfoListDto.getWeatherCode());
            fhIndexPostinfo.setAirPress(indexInfoListDto.getAirPress());
            fhIndexPostinfo.setFishIds(fishIds);
            fhIndexPostinfo.setLikes(0L);
            fhIndexPostinfo.setComments(0L);
            fhIndexPostinfo.setRetweets(0L);
            FhIndexPostinfo fhIndexPostinfoResult = fhIndexPostinfoService.insertFhIndexPostinfo(fhIndexPostinfo);
            /**
             * 插入发布细节表
             */
            for (int i = 0; i < postinfoDetailList.size(); i++) {
                FhIndexPostinfoDetail fhIndexPostinfoDetail = new FhIndexPostinfoDetail();
                fhIndexPostinfoDetail.setUserId(userId);
                fhIndexPostinfoDetail.setPostinfoId(fhIndexPostinfoResult.getId());
                fhIndexPostinfoDetail.setFishId(postinfoDetailList.get(i).getFishId());
                fhIndexPostinfoDetail.setWeight(postinfoDetailList.get(i).getWeight());
                fhIndexPostinfoDetail.setLength(postinfoDetailList.get(i).getLength());
                fhIndexPostinfoDetail.setCrateTime(LocalDateTime.now());
                fhIndexPostinfoDetailService.insert(fhIndexPostinfoDetail);
            }
            /**
             * 修改个人信息渔获记录表，已抓渔获数，已抓渔获ids，已抓鱼钟数，已抓鱼钟ids，最常见鱼种id，最常见鱼种图片
             */
            // 使用安全的方法获取渔获记录
            FhInfoCatchrecord fhInfoCatchrecord = getUniqueCatchrecord(userId);
//渔获数 这个个人的数据可能不存在 ，导致空指针异常
            try {
                if(fhInfoCatchrecord == null){
                    fhInfoCatchrecord = new FhInfoCatchrecord();
                    fhInfoCatchrecord.setUserId(userId);
                    fhInfoCatchrecord.setCatchNum(0L);
                    fhInfoCatchrecordService.insertFhInfoCatchrecord(fhInfoCatchrecord);
                }
            } catch (Exception e) {
                log.error("创建渔获记录失败", e);
                return R.fail("创建渔获记录失败");
            }
            Long catchNum = fhInfoCatchrecord.getCatchNum();
            catchNum += fishIdList.size();
            //渔获ids
            String catchNumids = fhInfoCatchrecord.getCatchNumids();
            String newCatchNumids;
            if (catchNumids == null|| catchNumids.isEmpty()) {
                newCatchNumids = fishIds;
            } else {
                newCatchNumids = catchNumids + "," + fishIds;
            }
            //计算已抓鱼种数,已抓鱼种ids
            String[] newCatchNumidsList = newCatchNumids.split(",");
            List<String> list = Arrays.asList(newCatchNumidsList);
            //List转HashSet去重
            Set<String> set = new HashSet<>(list);
            //HashSet转回List
            List<String> newCatchTypeIds = new ArrayList<>(set);
            long catchTypeNum = newCatchTypeIds.size();
            String catchTypeids = String.join(",", newCatchTypeIds);
            fhInfoCatchrecord.setCatchNum(catchNum);
            fhInfoCatchrecord.setCatchNumids(newCatchNumids);
            fhInfoCatchrecord.setCatchType(catchTypeNum);
            fhInfoCatchrecord.setCatchTypeids(catchTypeids);
            //查询最常见鱼类
            String[] newCatchNumidList = newCatchNumids.split(",");
            //计算该字符串中出现最多次数的元素
            String fishId = findMostFrequentChar(newCatchNumidList);
            long l = Long.parseLong(fishId);
            FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(l);
            fhInfoCatchrecord.setCommonFishid(l);
            fhInfoCatchrecord.setCommonFishimage(fhMapFishtype.getFishImage());
            fhInfoCatchrecordService.updateFhInfoCatchrecord(fhInfoCatchrecord);

            /**
             * 修改我的空间发布数量
             */
            FhInfoMyspace fhInfoMyspace = new FhInfoMyspace();
            fhInfoMyspace.setUserId(userId);
            List<FhInfoMyspace> fhInfoMyspaces = fhInfoMyspaceService.selectFhInfoMyspaceList(fhInfoMyspace);
            if (fhInfoMyspaces == null || fhInfoMyspaces.isEmpty()) {
                // 创建新的用户空间记录
                FhInfoMyspace newUserSpace = new FhInfoMyspace();
                newUserSpace.setUserId(userId);
                newUserSpace.setPostNum(1L);
                fhInfoMyspaceService.insertFhInfoMyspace(newUserSpace);
            } else {
                // 更新现有记录
                Long postNum = fhInfoMyspaces.get(0).getPostNum();
                postNum += 1;
                fhInfoMyspaces.get(0).setPostNum(postNum);
                fhInfoMyspaceService.updateFhInfoMyspace(fhInfoMyspaces.get(0));
            }

//            //修改发布渔获任务完成状态
//            compleTask(1L);

            // 插入发布动态任务日志（任务ID 1：发布动态）
            try {
                fhInfoUsertaskService.insertTaskLog(userId, 1L);
            } catch (Exception e) {
                log.warn("插入发布动态任务日志失败: " + e.getMessage());
            }

//            // 如果创建了钓点，插入发布标点任务日志（任务ID 5：发布标点）
//            if(indexInfoListDto.getLocationType().equals("1") && indexInfoListDto.getLongitude()!=null && indexInfoListDto.getLatitude()!=null && indexInfoListDto.getUserLocation()!=null && indexInfoListDto.getIscreatepun()!=null){
//                try {
//                    fhInfoUsertaskService.insertTaskLog(userId, 5L);
//                } catch (Exception e) {
//                    log.warn("插入发布标点任务日志失败: " + e.getMessage());
//                }
//            }

            //增加热点词使用人数
//            for (int i = 0; i < hot.size(); i++) {
//                FhIndexHot fhIndexHot = new FhIndexHot();
//                fhIndexHot.setHotWords(hot.get(i));
//                List<FhIndexHot> fhIndexHots = iFhIndexHotService.selectFhIndexHotList(fhIndexHot);
//                if(fhIndexHots!=null){
//                    FhIndexHot fhIndexHot1 = fhIndexHots.get(0);
//                    fhIndexHot1.setLikeNum(fhIndexHot1.getLikeNum()+1L);
//                    iFhIndexHotService.updateFhIndexHot(fhIndexHot1);
//                }
//            }

            //异步调用，修改此次发布位于的钓鱼点数据
            this.updateFishpoint(indexInfoListDto,fishIds);

            if(indexInfoListDto.getLocationType().equals("1") && indexInfoListDto.getLongitude()!=null && indexInfoListDto.getLatitude()!=null && indexInfoListDto.getUserLocation()!=null && indexInfoListDto.getIscreatepun()!=null){

                FhMypunctuation fhMypunctuation = new FhMypunctuation();
                fhMypunctuation.setAddress(indexInfoListDto.getAirPress());
                fhMypunctuation.setName(indexInfoListDto.getUserLocation()+"钓点");
                fhMypunctuation.setLatitude(indexInfoListDto.getLatitude());
                fhMypunctuation.setLongitude(indexInfoListDto.getLongitude());
                fhMypunctuation.setFishIds(fishIds);
                h5FhMypunctuationService.insert(fhMypunctuation);
            }


            return R.ok("发布成功");
        } catch (Exception e) {
            //手动强制回滚事务，这里一定要第一时间处理
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("发布信息失败", e);  // 添加日志记录
            return R.fail(e.getMessage());
        }
    }

    //异步调用，修改此次发布位于的钓鱼点数据,如果发布次数等于100，则添加到水域
    public void updateFishpoint(IndexInfoListDto indexInfoListDto,String fishIds){
        String longitude = indexInfoListDto.getLongitude();
        String latitude = indexInfoListDto.getLatitude();
        //根据经纬度查询附近钓鱼点
        FhInfoFishpoint fhInfoFishpoint = new FhInfoFishpoint();
        fhInfoFishpoint.setLongitude(longitude);
        fhInfoFishpoint.setDimension(latitude);
        List<FhInfoFishpoint> fhInfoFishpoints = fhInfoFishpointService.selectFhInfoFishpointList(fhInfoFishpoint);
        if(!fhInfoFishpoints.isEmpty()){
            FhInfoFishpoint fhInfoFishpointInfo = fhInfoFishpoints.get(0);
            String[] oldFishList = fhInfoFishpointInfo.getFishIds().split(",");
            String[] newFishList = fishIds.split(",");
            //使用set合并去重
            Set<String> set = new HashSet<>(Arrays.asList(oldFishList));
            set.addAll(Arrays.asList(newFishList));
            //set转换会数组
            String[] array = set.toArray(new String[0]);
            String join = String.join(",", array);
            //该钓鱼点发布次数加1
            Integer postNum = fhInfoFishpointInfo.getPostNum();
            postNum+=1;
            fhInfoFishpointInfo.setFishIds(join);
            fhInfoFishpointInfo.setPostNum(postNum);
            //更新钓鱼点
            fhInfoFishpointService.updateFhInfoFishpoint(fhInfoFishpointInfo);

            //如果该钓鱼点发布次数等于100则添加到水域
            if(postNum==100){
                FhMapWater fhMapWater = new FhMapWater();
                fhMapWater.setLongitude(fhInfoFishpointInfo.getLongitude());
                fhMapWater.setLatitude(fhInfoFishpointInfo.getDimension());
                fhMapWater.setWaterType("普通水域");
                fhMapWater.setWaterName(fhInfoFishpointInfo.getLocationName());
                fhMapWater.setCatchTotal(0L);
                fhMapWater.setCrateTime(new Date());
                fhMapWater.setUseStatus("0");
                fhMapWaterService.insertFhMapWater(fhMapWater);
            }
        }
    }

    //查找字符串数组中出现次数最多的字符串
    public static String findMostFrequentChar(String[] array) {
        Map<String, Integer> stringCountMap = new HashMap<>();
        for (String str : array) {
            stringCountMap.put(str, stringCountMap.getOrDefault(str, 0) + 1);
        }
        String mostFrequentString = null;
        int maxCount = 0;
        for (Map.Entry<String, Integer> entry : stringCountMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                mostFrequentString = entry.getKey();
            }
        }
        return mostFrequentString;
    }

    /**
     * 点赞发布信息
     */
    @UserLoginToken
    @ApiOperation("点赞发布信息")
    @PostMapping("/isLike")
    public R<String> isLike(Long postInfoId) {
        try {
            UserInfo localUserInfo = LocalUserInfoUtil.getLocalUserInfo();
            Long userId = localUserInfo.getId();
            FhIndexLike fhIndexLike = new FhIndexLike();
            fhIndexLike.setUserId(userId);
            fhIndexLike.setPostinfoId(postInfoId);
            //插入点赞表
            iFhIndexLikeService.insertFhIndexLike(fhIndexLike);
            //修改发布信息点赞数
            FhIndexPostinfo fhIndexPostinfo = fhIndexPostinfoService.selectFhIndexPostinfoById(postInfoId);
            Long likes = fhIndexPostinfo.getLikes();
            likes += 1;
            fhIndexPostinfo.setLikes(likes);
            fhIndexPostinfoService.updateFhIndexPostinfo(fhIndexPostinfo);

            //新增通知
            FhIndexMessage message = new FhIndexMessage();
            message.setMsgUserId(fhIndexPostinfo.getUserId());
            message.setName("点赞了你的消息");
            message.setUserId(Math.toIntExact(userId));
            message.setUserName(localUserInfo.getName());
            message.setUserUrl(localUserInfo.getImage());
            message.setType(1);
            message.setStatus(1);
            message.setCrateTime(LocalDateTime.now());
            fhIndexMessageService.insert(message);

            // 插入点赞任务日志（任务ID 4：点赞）
            try {
                fhInfoUsertaskService.insertTaskLog(userId, 4L);
            } catch (Exception e) {
                log.warn("插入点赞任务日志失败: " + e.getMessage());
            }

            return R.ok("点赞成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 取消点赞发布信息
     */
    @UserLoginToken
    @ApiOperation("删除点赞发布信息")
    @DeleteMapping("/noLike")
    public R<String> noLike(Long postInfoId) {
        try {
            UserInfo localUserInfo = LocalUserInfoUtil.getLocalUserInfo();
            Long userId = localUserInfo.getId();
            FhIndexLike fhIndexLike = new FhIndexLike();
            fhIndexLike.setUserId(userId);
            fhIndexLike.setPostinfoId(postInfoId);
            Long id = iFhIndexLikeService.selectFhIndexLikeList(fhIndexLike).get(0).getId();
            iFhIndexLikeService.deleteFhIndexLikeById(id);
            //修改发布信息点赞数
            FhIndexPostinfo fhIndexPostinfo = fhIndexPostinfoService.selectFhIndexPostinfoById(postInfoId);
            Long likes = fhIndexPostinfo.getLikes();
            likes -= 1;
            fhIndexPostinfo.setLikes(likes);
            fhIndexPostinfoService.updateFhIndexPostinfo(fhIndexPostinfo);

            //新增通知
            FhIndexMessage message = new FhIndexMessage();
            message.setMsgUserId(fhIndexPostinfo.getUserId());
            message.setName("取消了你的消息");
            message.setUserId(Math.toIntExact(userId));
            message.setUserName(localUserInfo.getName());
            message.setUserUrl(localUserInfo.getImage());
            message.setType(1);
            message.setStatus(1);
            message.setCrateTime(LocalDateTime.now());
            fhIndexMessageService.insert(message);


            return R.ok("取消点赞成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 首页热点表
     */
    @UserLoginToken
    @ApiOperation("获取热点表")
    @GetMapping("/hotList")
    public R<List<FhIndexHot>> hotList() {
        try {
            FhIndexHot fhIndexHot = new FhIndexHot();
            List<FhIndexHot> fhIndexHots = iFhIndexHotService.selectFhIndexHotList(fhIndexHot);
            fhIndexHots.sort(new Comparator<FhIndexHot>() {
                @Override
                public int compare(FhIndexHot o1, FhIndexHot o2) {
                    Long likeNum1 = o1.getLikeNum();
                    Long likeNum2 = o2.getLikeNum();
                    return likeNum2.compareTo(likeNum1);
                }
            });
            return R.ok(fhIndexHots);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    public R<String> compleTask(Long taskId) {
        try {
            //修改信息表
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();

            // 安全地获取用户信息（处理可能的重复数据）
            FhInfoUser fhInfoUserInfo = getUniqueUserInfo(userId);
            if (fhInfoUserInfo == null) {
                log.error("未找到用户信息或存在重复用户数据，用户ID: {}", userId);
                return R.fail("用户信息异常");
            }

            Long points = fhInfoUserInfo.getPoints();
            points += 10;
            fhInfoUserInfo.setPoints(points);
            fhInfoUserService.updateFhInfoUser(fhInfoUserInfo);

            //修改任务表状态，1为未完成，0为完成
            FhInfoUsertask fhInfoUsertask = new FhInfoUsertask();
            fhInfoUsertask.setUserId(userId);
            fhInfoUsertask.setTaskId(taskId);
            fhInfoUsertask.setCompletionStatus("0");
            fhInfoUsertaskService.updateFhInfoUsertaskByUserIdAndTaskId(fhInfoUsertask);

            return R.ok("完成成功");
        } catch (Exception e) {
            log.error("完成任务失败", e);
            return R.fail("完成任务失败: " + e.getMessage());
        }
    }


    /**
     * 安全地获取唯一的用户信息
     * @param userId 用户ID
     * @return 用户信息对象，如果不存在或存在重复则返回null
     */
    private FhInfoUser getUniqueUserInfo(Long userId) {
        try {
            // 使用查询列表方法替代selectOne
            FhInfoUser queryUser = new FhInfoUser();
            queryUser.setUserId(userId);
            List<FhInfoUser> userList = fhInfoUserService.selectFhInfoUserList(queryUser);

            if (userList == null || userList.isEmpty()) {
                log.warn("未找到用户信息，用户ID: {}", userId);
                return null;
            }

            if (userList.size() > 1) {
                log.warn("发现重复用户数据，用户ID: {}，记录数: {}", userId, userList.size());
                // 可以选择使用第一条记录，或者根据业务需求做其他处理
            }

            // 返回第一条记录
            return userList.get(0);
        } catch (Exception e) {
            log.error("查询用户信息异常，用户ID: {}", userId, e);
            return null;
        }
    }
    //好友渔获排名
    @ApiOperation("好友渔获排名")
    @PostMapping("/postInfoRanking")
    public R<PostInfoDtoX> postInfoRanking(@RequestBody PostinfoDto postinfo) throws IOException {
        PostInfoDtoX list = fhIndexPostinfoService.postInforanking(postinfo);
        return R.ok(list);
    }


    //渔获地区排名
    @ApiOperation("渔获地区排名")
    @PostMapping("/areaRanking")
    public R<PostInfoDtoX> areaRanking(@RequestBody PostinfoDto postinfo){
        PostInfoDtoX list = fhIndexPostinfoService.areaRanking(postinfo);
        return R.ok(list);

    }

    //获取已抓鱼种
    @ApiOperation("获取已抓鱼种")
    @PostMapping("/seizeFhsh")
    public ResponseEntity<PageImpl<FhMapFishtype>> seizeFhsh(@RequestBody PostinfoDto postinfo, Pageable page){
        List<FhMapFishtype> list = fhIndexPostinfoService.seizeFhsh(postinfo,page);
        return ResponseEntity.ok(new PageImpl<>(list, page, list.size()));

    }


    //获取附近鱼种
    @ApiOperation("获取附近鱼种")
    @PostMapping("/nearbyFish")
    public ResponseEntity<PageImpl<FhMapFishtype>> nearbyFish(@RequestBody PostinfoDto postinfo, Pageable page){
        List<FhMapFishtype> list = fhIndexPostinfoService.nearbyFish(postinfo,page);
        return ResponseEntity.ok(new PageImpl<>(list, page, list.size()));

    }

    @ApiOperation("查询通知列表列表")
    @PostMapping("/messzgeList")
    public ResponseEntity<Page<FhIndexMessage>> messzgeList(@RequestBody FhIndexMessageQuery query, Pageable page) {
        //获取用户id
        UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        query.setMsgUserId(member.getId());
        List<FhIndexMessage> list = fhIndexMessageService.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }


}
